<?php

/**
 * ECMall: SESSION �������
 * ============================================================================
 * ��Ȩ���� (C) 2005-2008 �Ϻ���������Ƽ����޹�˾������������Ȩ��
 * ��վ��ַ: http://www.shopex.cn
 * -------------------------------------------------------
 * �ⲻ��һ�������������ֻ���ڲ�������ҵĿ�ĵ�ǰ���¶Գ����������޸ĺ�ʹ�ã�
 * ������Գ���������κ���ʽ�κ�Ŀ�ĵ��ٷ�����
 * ============================================================================
 * $Id: cls.session.php 6009 2008-10-31 01:55:52Z Garbin $
 */

if (!defined('IN_ACHAO_ORG'))
{
    die('Hacking attempt');
}

class SessionProcessor
{
    var $db             = NULL;
    var $session_table  = '';
    var $session_data_table = '';

    var $max_life_time  = 1440; // SESSION ����ʱ��

    var $session_name   = '';
    var $session_id     = '';


    var $session_cookie_path   = '/';
    var $session_cookie_domain = '';
    var $session_cookie_secure = false;

    var $_ip   = '';

    var $_related_tables = array();

    /**
     * ���캯��
     *
     * @author wj
     * @param object $db ��ݿ����
     * @param stirng $session_table ��ݱ���
     * @param string $session_data_table ��ݴ洢����
     * @param string $session_name session���
     * @param string $session_id session_id
     * @return void
     */
    function __construct()
    {
        //$this->SessionProcessor($db, $session_table, $session_data_table, $session_name, $session_id);
    }

    /**
     * ���캯��
     *
     * @author weberliu
     * @param object $db ��ݿ����
     * @param stirng $session_table ��ݱ���
     * @param string $session_data_table ��ݴ洢����
     * @param string $session_name session���
     * @param string $session_id session_id
     * @return void
     */
    
	/*
	function SessionProcessor(&$db, $session_table, $session_data_table, $session_name = 'ECM_ID', $session_id = '')
    {
        session_set_save_handler(   array (& $this, "_sess_open"),
                                    array (& $this, "_sess_close"),
                                    array (& $this, "_sess_read"),
                                    array (& $this, "_sess_write"),
                                    array (& $this, "_sess_destroy"),
                                    array (& $this, "_sess_gc")
                                );
        $this->max_life_time = 1440;
        $this->session_cookie_path = COOKIE_PATH;
        $this->session_cookie_domain = COOKIE_DOMAIN;
        if (ENABLED_CUSTOM_DOMAIN)
        {
            $tmp_arr = parse_url(MAIN_DOMAIN);
            $this->session_cookie_domain = substr($tmp_arr['host'], strpos($tmp_arr['host'], '.'));
        }
        $this->session_cookie_secure = false;

        $this->session_name       = $session_name;
        $this->session_table      = $session_table;
        $this->session_data_table = $session_data_table;

        $this->db  = &$db;
        $this->_ip = real_ip();


        /*����session id* /
        if ($session_id == '' && !empty($_GET['sessid']))
        {
        	$this->session_id = $_GET['sessid'];
        	
        }elseif ($session_id == '' && !empty($_COOKIE[$this->session_name]))
        {
            $this->session_id = $_COOKIE[$this->session_name];
        }else
        {
            $this->session_id = $session_id;
        }

        if ($this->session_id)
        {
            $tmp_session_id = substr($this->session_id, 0, 32);

            if ($this->gen_session_key($tmp_session_id) == substr($this->session_id, 32))
            {
                $this->session_id = $tmp_session_id;
            }
            else
            {
                $this->session_id = '';
            }
        }

        if (!$this->session_id)
        {
            $this->gen_session_id();

            setcookie($this->session_name, $this->session_id . $this->gen_session_key($this->session_id), 0,
                $this->session_cookie_path, $this->session_cookie_domain, $this->session_cookie_secure);
           
        }
    }
*/	

    /**
     * open session handler
     *
     * @author wj
     * @param string $save_path
     * @param string $session_name
     * @return boolen
     */
    function _sess_open($save_path, $session_name)
    {
        return true;
    }

    /**
     * close session handler
     *
     * @author wj
     * @return boolen
     */
    function _sess_close()
    {
        return true;
    }

    /**
     * read session handler
     *
     * @author wj
     * @param string $sesskey
     * @return string
     */
    function _sess_read($sesskey)
    {

        $row = $this->db->getRow('SELECT data, expiry, is_overflow FROM ' . $this->session_table . " WHERE sesskey = '" . $this->session_id . "'");
        if (!empty($row))
        {
            if ($row['is_overflow'])
            {
                $row = $this->db->getRow('SELECT data, expiry FROM ' . $this->session_data_table . " WHERE sesskey = '" . $this->session_id . "'");
            }
        }
        else
        {
            $this->insert_session();
        }
            	    //	echo "read ",$row['data'] , "<br>";
		
        return isset($row['data']) ? base64_decode($row['data']) : '';

    }

    /**
     * write session handler
     *
     * @author Garbin
     * @param stirng $sesskey
     * @param string $sessvalue
     * @return boolen
     */
    function _sess_write($sesskey, $sessvalue)
    {
        //$sessvalue = addslashes($sessvalue);
        $adminid = !empty($_SESSION['admin_id']) ? intval($_SESSION['admin_id']) : 0;
        $userid  = !empty($_SESSION['user_id'])  ? intval($_SESSION['user_id'])  : 0;
        $username  = !empty($_SESSION['user_name'])  ? $_SESSION['user_name']  : 'NULL';
        $expiry  = $this->get_expiry();
        $is_overflow = 0;
        $sessvalue = base64_encode($sessvalue);
        if (isset($sessvalue{255}))
        {
        	$this->db->query( "REPLACE INTO `ecm_sessions_data` SET sesskey = '{$this->session_id}', expiry={$expiry}, data='{$sessvalue}'");
            $is_overflow = 1;
            $sessvalue = '';
        }
		
        return $this->db->query('UPDATE ' . $this->session_table . " SET expiry = '" . $expiry . "', ip = '" . $this->_ip . "', userid = '" . $userid . "', user_name='".$username."', adminid = '" . $adminid . "', data = '" . $sessvalue ."', is_overflow='" . $is_overflow . "' WHERE sesskey = '" . $this->session_id . "' LIMIT 1");

    }

    /**
     * destory session handler
     *
     * @author wj
     * @param stirng $sesskey
     * @return void
     */
    function _sess_destroy($sesskey)
    {
        $this->destroy_session();
    }

    /**
     * gc session handler ������session
     *
     * @author weberliu
     * @param int $maxlifetime
     * @return boolen
     */
    function _sess_gc($maxlifetime)
    {
        $time = time();
        /* ɾ�����session������Cart�������Ϣ */
        $expired_session = $this->db->getCol("SELECT s.sesskey ".
                                             "FROM `ecm_sessions` s ".
                                             "WHERE s.expiry < {$time}");
        if (!empty($this->_related_tables))
        {
            foreach ($this->_related_tables as $_t)
            {
                $this->db->query("DELETE FROM {$_t['name']} WHERE {$_t['ref_key']} " . db_create_in($expired_session));
            }
        }
        $this->db->query('DELETE FROM ' . $this->session_table . ' WHERE expiry < ' . $time);
        $this->db->query('DELETE FROM ' . $this->session_data_table . ' WHERE expiry < ' . $time);

        return true;
    }

    /**
     * ���session id
     *
     * @author wj
     * @return string
     */
    function gen_session_id()
    {
        $this->session_id = md5(uniqid(mt_rand(), true));

        return $this->insert_session();
    }

    /**
     * ���session��֤��
     *
     * @author wj
     * @param string $session_id
     * @return stirng
     */
    function gen_session_key($session_id)
    {
        static $ip = '';

        if ($ip == '')
        {
            $ip = substr($this->_ip, 0, strrpos($this->_ip, '.'));
        }

        return sprintf('%08x', crc32(!empty($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] . ROOT_PATH . $ip . $session_id : ROOT_PATH . $ip . $session_id));
    }

    /**
     * ����һ����session
     *
     * @author wj
     * @return void
     */
    function insert_session()
    {
        $adminid = !empty($_SESSION['admin_id']) ? intval($_SESSION['admin_id']) : 0;
        $userid  = !empty($_SESSION['user_id'])  ? intval($_SESSION['user_id'])  : 0;
        $username  = !empty($_SESSION['user_name'])  ? $_SESSION['user_name']  : 'NULL';

        $expiry  = $this->get_expiry();
        //echo 'INSERT INTO ' . $this->session_table . " SET sesskey = '" . $this->session_id . "', expiry = '" . $expiry . "', ip = '" . $this->_ip . "', userid = '" . $userid . "', adminid = '" . $adminid . "', data = ''";
        return $this->db->query('REPLACE INTO ' . $this->session_table . " SET sesskey = '" . $this->session_id . "', expiry = '" . $expiry . "', ip = '" . $this->_ip . "', userid = '" . $userid . "', user_name='".$username."', adminid = '" . $adminid . "', data = ''");
    }

    /**
     * ���ָ������Աsession
     *
     * @param int $adminid
     * @return boolen
     */
    function delete_spec_admin_session($adminid)
    {
        if (!empty($_SESSION['admin_id']) && $adminid)
        {
            return $this->db->query('DELETE FROM ' . $this->session_table . " WHERE adminid = '$adminid'");
        }
        else
        {
            return false;
        }
    }

    /**
     * ���һ��session
     *
     * @author wj
     * @return boolen
     */
    function destroy_session()
    {
        $_SESSION = array();
        setcookie($this->session_name, $this->session_id, 1, $this->session_cookie_path, $this->session_cookie_domain, $this->session_cookie_secure);
        /*
		if (!empty($this->_related_tables))
        {
            foreach ($this->_related_tables as $_t)
            {
                $this->db->query("DELETE FROM {$_t['name']} WHERE {$_t['ref_key']} = '{$this->session_id}'");
            }
        }
        $this->db->query('DELETE FROM ' . $this->session_data_table . " WHERE sesskey = '" . $this->session_id . "' LIMIT 1");
		*/
    }

    /**
     * ��ȡ��ǰsession id
     *
     * @author wj
     * @return string
     */
    function get_session_id()
    {
        return $this->session_id;
    }

    /**
     * ��ȡ�û���
     *
     * @author wj
     * @return int
     */
    function get_users_count()
    {
        $num = $this->db->getOne('SELECT count(*) FROM ' . $this->session_table . ' WHERE expiry >=' .time());

        return $num > 0 ? $num : 1;
    }

    /**
     * ��ӹ�j��
     *
     * @author wj
     * @param string $table_name
     * @param string $alias
     * @param string $related_key
     * @return void
     */
    function add_related_table($table_name, $alias, $related_key)
    {
        $this->_related_tables[] = array('name' => $table_name,
                                        'alias' => $alias,
                                        'ref_key' => $related_key);
    }

    /**
     * ��ȡ����ʱ��
     *
     * @author wj
     * @return void
     */
    function get_expiry()
    {
        return time() + $this->max_life_time;
    }

    /**
     * ��session
     *
     * @author wj
     * @return void
     */
    function my_session_start()
    {//$this->session_id
        return session_start();
    }
    
}

?>
